package com.ruoyi.common.utils.kingwow;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class KingwowUtils {

    private static final Logger logger = LoggerFactory.getLogger(KingwowUtils.class);
    public static final String jdbcDriver="com.mysql.jdbc.Driver";

    public static void testConnection(ConnParams params) throws SQLException {
        DataSource dataSource = getDataSource(params);
        Connection conn = null;
        Statement statement =null;
        try {
            conn = dataSource.getConnection();
            statement = conn.createStatement();
            ResultSet result = statement.executeQuery(params.getTestSql());
            result.next();
            int rst = result.getInt(1);
            logger.info("test connection sql:"+params.getTestSql()+",result:"+rst);
        } finally {
            if(statement!=null && !statement.isClosed()){
                statement.close();
            }
            if(conn!=null && !conn.isClosed()){
                conn.close();
            }
        }
    }

    public static DataSource getDataSource(ConnParams params)throws SQLException{
        String jdbcUrl = "jdbc:mysql://"+params.getDbHost()+":"+params.getDbPort()+"/"+params.getDbName();
        DriverManagerDataSource manager = new DriverManagerDataSource();
        manager.setDriverClassName(jdbcDriver);
        manager.setUrl(jdbcUrl);
        manager.setUsername(params.getJdbcUser());
        manager.setPassword(params.getJdbcPass());
        return manager;
    }

}
